package com.dongnam.quanly.web.nghiepvu.muabanhang.donhang;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.model.SelectItem;

import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.ChiTietDonHangController;
import com.dongnam.quanly.common.controller.DonHangController;
import com.dongnam.quanly.common.controller.VatTuHangHoaController;
import com.dongnam.quanly.common.model.ChiTietDonHang;
import com.dongnam.quanly.common.model.DonHang;
import com.dongnam.quanly.common.model.PhieuNhapXuat;
import com.dongnam.quanly.common.model.enumtype.LoaiDonHang;
import com.dongnam.quanly.common.model.enumtype.PhuongTienVanChuyen;
import com.dongnam.quanly.common.model.enumtype.TrangThaiDonHang;
import com.dongnam.quanly.common.util.CreateIDUtil;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.LocaleMessages;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "DonHangBean")
@SessionScoped
public class DonHangBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(DonHangBean.class);

	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;

	private DonHang donHang;
	private boolean isEdit = false;
	private String loaiDonHang;

	

	private DonHangController donHangController;
	private VatTuHangHoaController vthhController;
	private ChiTietDonHangController chitietdonhangController;

	private List<DonHang> listDonHang;
	private List<DonHang> listDonHangFiltered;
	private SelectItem[] loaiDonHangSelectItems;

	// for store list PO
	private List<ChiTietDonHang> listPODetail;
	private List<ChiTietDonHang> listPODetailOriginal;

	private ChiTietDonHang selectedProductOrderDetail;

	private String soDonHang;
	private String maVthh;
	private int soluong;
	private double dongia;

	private DonHang selectedDonHang;
	
	// for download danh sach don hang
	private String loaiFile;
	private StreamedContent file;
	
	public DonHangBean() {
		super();
		donHang = new DonHang();
		listDonHang = new ArrayList<DonHang>();
		loadDonHang();

		createLoaiDonHangSelectItems();
	}

	public String checkDate(Date value) {
		if (null == value) {
			return " ";
		} else {
			return value.toString();
		}
	}
	
	public void downloadPurchaseOders()
	{
		
	}
	public void downloadFileCSV() {
		// Todo
		File excelfile = new File("Don_Hang.xls");
		List<DonHang> list = getDonHangController().findAll("orderNumber", "DESCENDING");
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);
			sheet.setColumnView(9, 30);
			sheet.setColumnView(10, 30);
			sheet.setColumnView(11, 30);

			sheet.addCell(new Label(0, 0, "Số Chứng Từ", titleformat));
			sheet.addCell(new Label(1, 0, "Ngày Lập ", titleformat));
			sheet.addCell(new Label(2, 0, "Phương Tiện Vận chuyển", titleformat));
			sheet.addCell(new Label(3, 0, "Người Giao Hàng", titleformat));
			sheet.addCell(new Label(4, 0, "Số Điện Thoại ", titleformat));
			sheet.addCell(new Label(5, 0, "Đối Tác", titleformat));
			sheet.addCell(new Label(6, 0, "Cá Nhân", titleformat));
			sheet.addCell(new Label(7, 0, "Nhân Viên Nhận", titleformat));
			sheet.addCell(new Label(8, 0, "Kho Hàng Nhận", titleformat));
			sheet.addCell(new Label(9, 0, "Kho Hàng Xuất", titleformat));
			sheet.addCell(new Label(10, 0, "Loại Đơn Hàng", titleformat));
			sheet.addCell(new Label(11, 0, "Trạng Thái", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getSoChungTu(), contentformat));
				sheet.addCell(new Label(1, i + 1, checkDate(list.get(i).getNgayLap()), contentformat));

				sheet.addCell(new Label(2, i + 1, list.get(i).getPhuongTienVanChuyen().name(), contentformat));
				sheet.addCell(new Label(3, i + 1, list.get(i).getNguoiGiaoHang(), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getSoDTNguoiGiaoHang(), contentformat));
				sheet.addCell(new Label(5, i + 1, list.get(i).getDoiTac(), contentformat));
				sheet.addCell(new Label(6, i + 1, list.get(i).getCaNhan(), contentformat));
				sheet.addCell(new Label(7, i + 1, list.get(i).getNhanVienNhan(), contentformat));
				sheet.addCell(new Label(8, i + 1, list.get(i).getKhoNhanHang(), contentformat));
				sheet.addCell(new Label(9, i + 1, list.get(i).getKhoXuatHang(), contentformat));
				sheet.addCell(new Label(10, i + 1, list.get(i).getLoaiDonHang().name(), contentformat));
				sheet.addCell(new Label(11, i + 1, list.get(i).getTrangThai().name(), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "Don_Hang.xls", "UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void handleFileUpload(FileUploadEvent event) {
		// ToDo
		logger.debug("process upload file : DonHang.xls ");
		Workbook w;
		boolean rollback = false;
		List<DonHang> list = new ArrayList<DonHang>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);

				DonHang dh = new DonHang();

				list.add(dh);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : " + e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getDonHangController().batchSaveOrUpdate(list);
		}

		loadDonHang();
	}

	public void resetFormAdd() {
		donHang = new DonHang();
	}

	public void notifyAdd() {
		isEdit = false;

		resetFormAdd();
		// this.soDonHang = CreateIDUtil.createDonHangID();
		// this.donHang.setSoChungTu(this.soDonHang);

		if (listPODetail == null)
			listPODetail = new ArrayList<ChiTietDonHang>();
		listPODetail.clear();
	}

	public void notifyEdit(DonHang donHang) {
		isEdit = true;
		this.donHang = new DonHang(donHang);
		this.soDonHang = this.donHang.getSoChungTu();
		if (listPODetail == null)
			listPODetail = new ArrayList<ChiTietDonHang>();
		listPODetail.clear();
		this.listPODetail = getChitietdonhangController().getListCtdh(this.donHang.getSoChungTu());

		// xoa toan bo chitietdon hang nay trong datase
		this.listPODetailOriginal = new ArrayList<ChiTietDonHang>();
		for (int i = 0; i < this.listPODetail.size(); i++) {
			ChiTietDonHang ctdh = new ChiTietDonHang(this.listPODetail.get(i));
			this.listPODetailOriginal.add(ctdh);
		}
		// ToDo
		// this.nhanvien.fillNhanVien(nhanvien);
	}

	public List<ChiTietDonHang> getListPODetailOriginal() {
		return listPODetailOriginal;
	}

	public void setListPODetailOriginal(List<ChiTietDonHang> listPODetailOriginal) {
		this.listPODetailOriginal = listPODetailOriginal;
	}

	public void removeDonHang() {

		if (this.selectedDonHang != null) {
			// ToDo
			try {
				List<ChiTietDonHang> list = getChitietdonhangController().getListCtdh(this.selectedDonHang.getSoChungTu());

				getChitietdonhangController().batchDelete(list);
				getDonHangController().makeTransient(this.selectedDonHang);

				this.listDonHang.remove(this.selectedDonHang);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	public void resetProductOrderDetail() {
		this.maVthh = "";
		this.soluong = 0;
		this.dongia = 0.0;
	}

	public void notifyAddChiTietDonHang() {
		resetProductOrderDetail();
		if (this.listPODetail == null || this.listPODetail.size() == 0)
			this.listPODetail = new ArrayList<ChiTietDonHang>();
	}

	public void save() {
		RequestContext context = RequestContext.getCurrentInstance();

		// save Don Hang
		this.donHang.setOrderNumber(Long.parseLong(this.getSoDonHang().substring(5)));
		getDonHangController().makePersistent(this.donHang);

		if (isEdit)
			getChitietdonhangController().batchDelete(this.listPODetailOriginal);

		getChitietdonhangController().batchPersist(this.listPODetail);
		loadDonHang();
		context.addCallbackParam("opSuccess", true);
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public DonHang getDonHang() {
		return donHang;
	}

	public void setDonHang(DonHang donHang) {
		this.donHang = donHang;
	}

	public String getLoaiFile() {
		return loaiFile;
	}

	public void setLoaiFile(String loaiFile) {
		this.loaiFile = loaiFile;
	}

	public boolean isEdit() {
		return isEdit;
	}

	public void setEdit(boolean isEdit) {
		this.isEdit = isEdit;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public DonHangController getDonHangController() {

		if (donHangController == null) {
			donHangController = new DonHangController();
		}

		return donHangController;
	}

	public void setDonHangController(DonHangController donHangController) {
		this.donHangController = donHangController;
	}

	public List<DonHang> getListDonHang() {
		return listDonHang;
	}

	public void setListDonHang(List<DonHang> listDonHang) {
		this.listDonHang = listDonHang;
	}

	public DonHang getSelectedDonHang() {
		return selectedDonHang;
	}

	public void setSelectedDonHang(DonHang selectedDonHang) {
		this.selectedDonHang = selectedDonHang;
	}

	public PhuongTienVanChuyen[] getListPhuongTienVanChuyen() {
		return PhuongTienVanChuyen.values();
	}

	public LoaiDonHang[] getListLoaiDonHang() {
		return LoaiDonHang.values();
	}

	public void createLoaiDonHangSelectItems() {
		int length = LoaiDonHang.values().length;
		LoaiDonHang[] list = LoaiDonHang.values();
		loaiDonHangSelectItems = new SelectItem[length];
		for (int i = 0; i < length; i++) {
			loaiDonHangSelectItems[i] = new SelectItem(list[i], list[i].name());
		}
	}

	public TrangThaiDonHang[] getListTrangThai() {
		return TrangThaiDonHang.values();
	}

	private void loadDonHang() {
		this.listDonHang = getDonHangController().findAll("orderNumber", "DESCENDING");
	}

	public ChiTietDonHangController getChitietdonhangController() {

		if (chitietdonhangController == null)
			chitietdonhangController = new ChiTietDonHangController();

		return chitietdonhangController;
	}

	public void setChitietdonhangController(ChiTietDonHangController chitietdonhangController) {
		this.chitietdonhangController = chitietdonhangController;
	}

	public VatTuHangHoaController getVthhController() {
		if (vthhController == null)
			vthhController = new VatTuHangHoaController();
		return vthhController;
	}

	public void setVthhController(VatTuHangHoaController vthhController) {
		this.vthhController = vthhController;
	}

	public List<ChiTietDonHang> getListPODetail() {
		return listPODetail;
	}

	public void setListPODetail(List<ChiTietDonHang> listPODetail) {
		this.listPODetail = listPODetail;
	}

	public ChiTietDonHang getSelectedProductOrderDetail() {
		return selectedProductOrderDetail;
	}

	public void setSelectedProductOrderDetail(ChiTietDonHang selectedProductOrderDetail) {
		this.selectedProductOrderDetail = selectedProductOrderDetail;
	}

	public String getSoDonHang() {
		return soDonHang;
	}

	public void setSoDonHang(String soDonHang) {
		this.soDonHang = soDonHang;
	}

	public String getMaVthh() {
		return maVthh;
	}

	public void setMaVthh(String maVthh) {
		this.maVthh = maVthh;
	}

	public int getSoluong() {
		return soluong;
	}

	public void setSoluong(int soluong) {
		this.soluong = soluong;
	}

	public double getDongia() {
		return dongia;
	}

	public void setDongia(double dongia) {
		this.dongia = dongia;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public void saveChiTietDonHang() {
		try {
			RequestContext context = RequestContext.getCurrentInstance();
			logger.debug("Add Chi Tiet Don Hang " + this.soDonHang + "   " + this.maVthh);
			String tenVthh = getVthhController().getById(this.maVthh, true).getTenVTHH();
			ChiTietDonHang ctdh = new ChiTietDonHang(this.soDonHang, this.maVthh, tenVthh, this.soluong, this.dongia);
			listPODetail.add(ctdh);
			context.addCallbackParam("opSuccess", true);
			logger.debug("So Luong" + listPODetail.size());
		} catch (Exception e) {

		}
	}

	public void removeChiTietDonHang() {
		this.listPODetail.remove(this.selectedProductOrderDetail);
	}

	public void changeLoaiDonHang(AjaxBehaviorEvent event) {
		LoaiDonHang loaiDonHang = (LoaiDonHang) ((UIOutput) event.getSource()).getValue();

		this.loaiDonHang = loaiDonHang.name();
		logger.info("ndakdnak " + this.loaiDonHang);

		this.soDonHang = CreateIDUtil.createDonHangID(loaiDonHang);
		this.donHang.setSoChungTu(this.soDonHang);

	}

	public String getLoaiDonHang() {
		return loaiDonHang;
	}

	public void setLoaiDonHang(String loaiDonHang) {
		this.loaiDonHang = loaiDonHang;
	}

	public List<DonHang> getListDonHangFiltered() {
		return listDonHangFiltered;
	}

	public void setListDonHangFiltered(List<DonHang> listDonHangFiltered) {
		this.listDonHangFiltered = listDonHangFiltered;
	}

	public SelectItem[] getLoaiDonHangSelectItems() {
		return loaiDonHangSelectItems;
	}

	public void setLoaiDonHangSelectItems(SelectItem[] loaiDonHangSelectItems) {
		this.loaiDonHangSelectItems = loaiDonHangSelectItems;
	}

	public void reloadPage() {
		loadDonHang();
		resetFormAdd();
		resetProductOrderDetail();
		WebUtil.redirect("/pages/nghiepvu/muabanhang/donHang.xhtml");
	}

	public void editOrderStatusCell(RowEditEvent event) {
		try {
			DonHang donhang = (DonHang) event.getObject();
			
			getDonHangController().makePersistent(donhang);
			
			FacesMessage message = LocaleMessages.getMessage("general_edit_success");
			message.setSeverity(FacesMessage.SEVERITY_INFO);
			FacesContext.getCurrentInstance().addMessage(null, message);
			
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessage message = LocaleMessages.getMessage("general_edit_fail");
			message.setSeverity(FacesMessage.SEVERITY_INFO);
			FacesContext.getCurrentInstance().addMessage(null, message);
		}
		
	
	}
}
